﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Navigation;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.StorageHelper;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views.CacheDownload
{
    public partial class ComicChapterPage : PhoneApplicationPage
    {
        private bool IsReloadData = false;
        private string comicId = string.Empty, comicSource = string.Empty;
        private string comicCoverUrl = string.Empty, comicTitle = string.Empty;

        public ComicChapterPage()
        {
            InitializeComponent();
            IsReloadData = true;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            IsReloadData = false;
            //
            var items = Helper.FindChildren<ToggleButton>(this.longListSelector);
            if (items == null)
                return;
            foreach (ToggleButton item in items)
            {
                if (item == null)
                    continue;
                item.IsChecked = false;
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            base.NavigationContext.QueryString.TryGetValue("comicId", out comicId);
            if (string.IsNullOrWhiteSpace(comicId))
            {
                base.NavigationService.GoBack();
                return;
            }
            base.NavigationContext.QueryString.TryGetValue("comicSource", out comicSource);
            if (!string.IsNullOrWhiteSpace(comicSource))
                this.txtComicSource.Text = string.Format("来源站点：{0}", comicSource);
            else
                this.txtComicSource.Text = "默认站点";
            base.NavigationContext.QueryString.TryGetValue("comicCoverUrl", out comicCoverUrl);
            base.NavigationContext.QueryString.TryGetValue("comicTitle", out comicTitle);
            this.txtTitle.Text = this.comicTitle;
            if (this.IsReloadData)
            {
                LoadComicChapter(comicId);
            }
        }

        private void longListSelector_Loaded(object sender, RoutedEventArgs e)
        {
            RefreshChapterCacheFlag();
        }

        void RefreshChapterCacheFlag()
        {
            var items = Helper.FindChildren<ToggleButton>(this.longListSelector);
            if (items == null)
                return;

            if (!IsolatedStorageHelper.Instance.FileExists(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE))
                return;

            string localCacheData = IsolatedStorageHelper.Instance.ReadText(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE);
            if (string.IsNullOrWhiteSpace(localCacheData))
                return;
            var localCacheItems = JSONHelper.Deserialize<ObservableCollection<DownloadComic>>(localCacheData);
            if (!(localCacheItems != null && localCacheItems.Count > 0))
            {
                return;
            }
            var localCacheItem = localCacheItems.Where(p => p.ComicId.ToString().Equals(this.comicId)).FirstOrDefault<DownloadComic>();
            if (localCacheItem == null)
                return;
            foreach (ToggleButton item in items)
            {
                if (item == null)
                    continue;
                var chapter = item.DataContext as JsonComicChapterInfoBookPartList;
                if (chapter == null)
                    continue;
                var isExist = (from p in localCacheItem.Chapters where p.PartId == chapter.PartId select p).FirstOrDefault<DownloadComicChapter>();
                if (isExist != null)
                {
                    item.IsChecked = true;
                }
            }
        }


        public void LoadComicChapter(string comicId)
        {
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/downloadcomicsview_v3?bookid=", comicId.ToString());

            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                //无需重新加载数据
                var rootCharacterString = JSONHelper.Deserialize<JsonComicChapter>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.BookPartList != null && rootCharacterString.Info.BookPartList.Count > 0))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    this.longListSelector.ItemsSource = rootCharacterString.Info.BookPartList;
                }
                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        if (result.IndexOf("\"info\":{}") >= 0)
                        {
                            LogHelper.LogError("未找到对应漫画！", this.GetType(), MethodBase.GetCurrentMethod());
                            return;
                        }
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicChapter>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.BookPartList != null && rootCharacterString.Info.BookPartList.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                            this.Dispatcher.BeginInvoke(() =>
                            {
                                this.longListSelector.ItemsSource = rootCharacterString.Info.BookPartList;
                            });
                        }

                        #endregion 获取结果处理
                    });
                }
                catch (Exception err)
                {

                }
            }, webTask);
        }


        private void tgbtnComicChapter_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = sender as ToggleButton;
            if (item == null)
                return;
            bool isChecked = Convert.ToBoolean(item.IsChecked);
            this.SetCheckStatus(isChecked, item);
        }

        private void appBarCheck_Click(object sender, EventArgs e)
        {
            var appBarIcon = sender as ApplicationBarIconButton;
            if (appBarIcon == null)
                return;

            this.Dispatcher.BeginInvoke(() =>
            {
                var items = this.longListSelector.ItemsSource as ObservableCollection<JsonComicChapterInfoBookPartList>;

                if ("选择全部".Equals(appBarIcon.Text))
                {
                    appBarIcon.Text = "取消全选";
                    appBarIcon.IconUri = new Uri("/Images/Icons/uncheckedall.png", UriKind.Relative);
                    SetCheckStatus(true);
                }
                else
                {
                    appBarIcon.Text = "选择全部";
                    appBarIcon.IconUri = new Uri("/Images/Icons/checkedall.png", UriKind.Relative);
                    SetCheckStatus(false);
                }
            });
        }

        void SetCheckStatus(bool status, ToggleButton tgb = null)
        {
            var items = Helper.FindChildren<ToggleButton>(this.longListSelector);
            if (items == null)
                return;

            if (tgb != null)
            {
                foreach (ToggleButton item in items)
                {
                    if (item == tgb)
                    {
                        item.IsChecked = status;
                        break;
                    }
                }
            }
            else
            {
                foreach (ToggleButton item in items)
                {
                    item.IsChecked = status;
                }
            }

            items = Helper.FindChildren<ToggleButton>(this.longListSelector);
            int count = 0;
            foreach (ToggleButton item in items)
            {
                if (item == null)
                    continue;
                if (Convert.ToBoolean(item.IsChecked))
                    count++;
                if (count > 0)
                    this.txtSelectedTip.Text = string.Format("共选择{0}章", count);
                else
                    this.txtSelectedTip.Text = "请选择要下载的章节";
            }
        }

        private void appBarSort_Click(object sender, EventArgs e)
        {
            var appBarIcon = sender as ApplicationBarIconButton;
            if (appBarIcon == null)
                return;
            this.Dispatcher.BeginInvoke(() =>
            {
                var items = this.longListSelector.ItemsSource as ObservableCollection<JsonComicChapterInfoBookPartList>;

                if ("倒序z~a".Equals(appBarIcon.Text))
                {
                    appBarIcon.Text = "正序a~z";
                    appBarIcon.IconUri = new Uri("/Images/Icons/sortasc.png", UriKind.Relative);
                    this.longListSelector.ItemsSource = new ObservableCollection<JsonComicChapterInfoBookPartList>(items.OrderByDescending(p => p.PartId).ToList<JsonComicChapterInfoBookPartList>());
                }
                else
                {
                    appBarIcon.Text = "倒序z~a";
                    appBarIcon.IconUri = new Uri("/Images/Icons/sortdesc.png", UriKind.Relative);
                    this.longListSelector.ItemsSource = new ObservableCollection<JsonComicChapterInfoBookPartList>(items.OrderBy(p => p.PartId).ToList<JsonComicChapterInfoBookPartList>());
                }
            });
        }

        private void appBarConfirm_Click(object sender, EventArgs e)
        {
            ObservableCollection<DownloadComicChapter> chapters = new ObservableCollection<DownloadComicChapter>();
            var items = Helper.FindChildren<ToggleButton>(this.longListSelector);
            //读取历史
            DownloadComic existDownloadComic = null;
            if (IsolatedStorageHelper.Instance.FileExists(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE))
            {
                string localCacheData = IsolatedStorageHelper.Instance.ReadText(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE);
                if (!string.IsNullOrWhiteSpace(localCacheData))
                {
                    var localCacheItems = JSONHelper.Deserialize<ObservableCollection<DownloadComic>>(localCacheData);
                    if (localCacheItems != null && localCacheItems.Count > 0)
                    {
                        existDownloadComic = localCacheItems.Where(p => p.ComicId.ToString().Equals(this.comicId)).FirstOrDefault<DownloadComic>();
                    }
                }
            }
            //
            foreach (ToggleButton item in items)
            {
                if (item == null)
                    continue;
                if (!Convert.ToBoolean(item.IsChecked))
                    continue;

                var chapter = item.DataContext as JsonComicChapterInfoBookPartList;
                if (chapter != null)
                {
                    //判断是否已经加入下载队列
                    if (existDownloadComic != null && existDownloadComic.Chapters != null && existDownloadComic.Chapters.Count > 0)
                    {
                        var isExist = (from p in existDownloadComic.Chapters where p.PartId == chapter.PartId select p).FirstOrDefault<DownloadComicChapter>();
                        if (isExist != null)
                        {
                            continue;//已经存在于下载队列
                        }
                    }
                    chapters.Add(new DownloadComicChapter()
                    {
                        Name = chapter.Name,
                        PartId = chapter.PartId,
                        Partsize = chapter.Partsize,
                        Partnumber = chapter.Partnumber,
                        DownloadStatus = (int)DownloadComicChapterStatus.Pending,
                        Totalpage = chapter.Totalpage,
                        Msourceparturl = chapter.Msourceparturl,
                        Sourceparturl = chapter.Sourceparturl
                    });
                }
            }
            if (chapters.Count() > 0)
            {
                if (MessageBoxResult.OK == MessageBox.Show(string.Format("您共选择了 {0} 章节，确认下载吗？", chapters.Count()), AppResources.ApplicationTitle, MessageBoxButton.OKCancel))
                {
                    //TODO 跳转至下载漫画列表页
                    DownloadComic comic = new DownloadComic();
                    comic.ComicId = Convert.ToInt32(this.comicId);
                    comic.ComicTitle = this.comicTitle;
                    comic.CoverUrl = this.comicCoverUrl;
                    comic.Chapters = chapters;
                    foreach (var item in comic.Chapters)
                    {
                        item.ComicId = comic.ComicId;
                        item.ComicIdAndPartId = string.Concat(item.ComicId, "#", item.PartId);
                    }
                    comic.DownloadStatus = (int)DownloadComicChapterStatus.Pending;
                    NaviService.Navigate(ComicIslandPage.CDComicChapterCacheQueuePage, string.Concat("?DownloadComic=", Uri.EscapeDataString(JSONHelper.Serialize<DownloadComic>(comic))));
                }
            }
            else
            {
                MessageToastManager.Show("您还未选择要下载的漫画章节！", MessageToastLevel.Warn);
            }
        }

        private void appBarDownManage_Click(object sender, EventArgs e)
        {
            NaviService.Navigate(ComicIslandPage.CDCacheManagePage);
        }



    }
}